package com.onluy.frameworkcloud.mvc.annotation;


import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;


public class DateWebBindingInitializer implements WebBindingInitializer {

    private   String format="yyyy-MM-dd HH:mm:ss";
    public String getFormat() {
        return format;
    }

    public void setFormat(String format) {
        this.format = format;
    }

    @Override
    public void initBinder(WebDataBinder binder) {
        DateFormat dateFormat = new SimpleDateFormat(getFormat());
        binder.registerCustomEditor(Date.class,new PropertyEditorSupport() {

            @Override
            public String getAsText() {
                return new SimpleDateFormat(format)  .format((Date) getValue());
            }

            public void setAsText(String text) {
                try {
                    if(text==null ){
                       setValue(null);
                   }
                   else if(  text.length()== 10){
                       setValue(new SimpleDateFormat("yyyy-MM-dd").parse(text));
                   }
                   else if(  text.length()== format.length()){
                       setValue(new SimpleDateFormat(format).parse(text));
                   }else{
                        setValue(null);
                    }
                } catch (Exception e) {
                        setValue(null);
                }
            }
        });
    }
}
